package com.vains.config.feign;

import com.vains.utils.SpringContextUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * Feign请求拦截器 解决请求头丢失的问题
 * @author vians
 */
public class FeignBasicAuthRequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        HttpServletRequest request = SpringContextUtils.getCurrentRequest();
        // Assert.notNull(request, "获取当前request对象失败!");
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                String values = request.getHeader(name);
                requestTemplate.header(name, values);
            }
        }

        // 获取basic认证
        String headers = (String) request.getAttribute("authorizationHeader");
        if (!StringUtils.isEmpty(headers)) {
            requestTemplate.header("Authorization", headers);
        }
        // 判断参数
        /*String accessToken = request.getParameter("access_token");
        if (!StringUtils.isEmpty(accessToken)) {
            List<String> values = new ArrayList<>();
            values.add(accessToken);
            requestTemplate.queries().put("access_token", Collections.unmodifiableList(values));
        }*/
    }
}